﻿using UnityEngine;

public abstract class HexagonNode : MonoBehaviour
{
    protected Vector2 p;
    protected static bool is2D;
    protected static Mesh mesh;
    protected MeshRenderer render;
    protected static readonly float g3 = Mathf.Sqrt(3);
    public static readonly Vector3 width = new(1, 0, 0.5f);
    public static readonly Vector3 height = new(0, 0, 1);
    protected static Vector3[] vertices;
    protected static int[] triangles;
    protected static Vector2[] uv;
    protected static Vector3[] normals;
    public void Draw(int x, int y, Material material = null)
    {
        if (mesh == null)
        {
            mesh = new Mesh
            {
                vertices = vertices,
                triangles = triangles,
                uv = uv,
                normals = normals
            };
        }
        GetComponent<MeshFilter>().mesh = mesh;
        if (render == null)
            render = GetComponent<MeshRenderer>();
        if (material != null)
            render.material = material;
        p.x = x; p.y = y;
        gameObject.SetActive(true);
        //gameObject.name = p.x + "," + p.y;
        transform.localPosition = p.x * width + p.y * height - (p.y - p.y % 2) * width / 2;
        if (!is2D)
        {
            var p3 = transform.localPosition;
            p3.z = p3.y;
            p3.y = 0;
            transform.localPosition = p3;
            transform.localEulerAngles = new Vector3(90, 90, 0);
        }
    }
}

[ExecuteAlways]
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class HexagonRect : HexagonNode
{
    private void Awake()
    {
        vertices = new Vector3[] {
            new (0.75f,g3/2),
            new (0.75f,-g3/2),
            new (-0.75f,-g3/2),
            new (-0.75f,g3/2),
        };
        triangles = new int[] { 0, 1, 2, 0, 2, 3 };
        uv = new Vector2[]
        {
            new (0.75f,g3/2),
            new (0.75f,-g3/2),
            new (-0.75f,-g3/2),
            new (-0.75f,g3/2),
        };
        normals = new Vector3[]
        {
            -Vector3.forward,-Vector3.forward,-Vector3.forward,-Vector3.forward
        };
        Draw(0, 0);
    }
}
